import type { EventHandlerRequest, H3Event } from 'h3';
import { AdminUserModel } from '../models/admin_user.model';

/**
 * 检查管理员用户是否已登录
 * @param { H3Event } event H3 Event
 * @returns { Promise<{ status: boolean; user: any }> }
 */
export function adminIsLogin(event: H3Event<EventHandlerRequest>): Promise<{
	status: boolean;
	user: any;
}> {
	return new Promise(async (resolve, reject) => {
		const authorization: string | undefined = getRequestHeader(event, 'Authorization');

		if (typeof authorization !== 'string' || !authorization.startsWith('Bearer ')) {
			reject(new Error('无效的 Token'));
			return;
		}

		// 读取 Token
		const token: string = authorization.split(' ')[1];

		try {
			// 验证 Token
			const decoded: any = await verifyToken(token);

			const findResult = await AdminUserModel.findById(decoded.id);

			if (findResult !== null) {
				resolve({
					status: true,
					user: findResult,
				});
			} else {
				reject({
					status: false,
					user: null,
				});
			}
		} catch (err: any) {
			error(err);
			reject({
				status: false,
				user: null,
			});
		}
	});
}

/**
 * 检查管理员用户是否具有指定权限
 * @param { H3Event } event H3 Event
 * @param { string } permissionName 权限名称
 * @returns { boolean }
 */
export function checkAdminUserPermission(
	event: H3Event<EventHandlerRequest>,
	permissionName: string | string[]
): boolean {
	// 验证用户权限
	const { user } = event.context;
	const allowPermission = ['admin'];
	if (Array.isArray(permissionName)) {
		return allowPermission.includes(user.permission);
	}
	return user.permission === permissionName;
}
